import { ORDER_TOKEN, loginAPI } from '@/apis'
import { useNavigate } from 'react-router-dom'
import { zodResolver } from '@hookform/resolvers/zod'
import { useForm } from 'react-hook-form'
import { z } from 'zod'
import { Button } from '@/components/ui/button'
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from '@/components/ui/form'
import { Input } from '@/components/ui/input'
import { useToast } from '@/components/ui/use-toast'

const FormSchema = z.object({
  account: z.string().min(1, {
    message: '请输入账户名',
  }),
  password: z.string().min(1, {
    message: '请输入密码',
  }),
})

const Login = () => {
  const navigate = useNavigate()
  const { toast } = useToast()

  const form = useForm<z.infer<typeof FormSchema>>({
    resolver: zodResolver(FormSchema),
    defaultValues: {
      account: 'zhousg',
      password: '123456',
    },
  })

  async function onSubmit(data: z.infer<typeof FormSchema>) {
    try {
      const res = await loginAPI(data)
      localStorage.setItem(ORDER_TOKEN, res.data.result.token)
      navigate('/')
    } catch (error: any) {
      console.log(error)
      toast({
        variant: 'destructive',
        title: 'sorry, login error',
        description: error.response.data.message,
      })
    }
  }

  return (
    <div className="flex justify-center">
      <Form {...form}>
        <form
          onSubmit={form.handleSubmit(onSubmit)}
          className="w-2/3 space-y-6">
          <FormField
            control={form.control}
            name="account"
            render={({ field }) => (
              <FormItem>
                <FormLabel>账号</FormLabel>
                <FormControl>
                  <Input placeholder="请输入账号" {...field} />
                </FormControl>
                <FormMessage />
              </FormItem>
            )}
          />
          <FormField
            control={form.control}
            name="password"
            render={({ field }) => (
              <FormItem>
                <FormLabel>密码</FormLabel>
                <FormControl>
                  <Input placeholder="请输入密码" {...field} />
                </FormControl>
                <FormMessage />
              </FormItem>
            )}
          />
          <Button type="submit">登录</Button>
        </form>
      </Form>
    </div>
  )
}

export default Login
